package com.example.barcodeapp.ui.wode.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


import com.example.barcodeapp.R;
import com.example.barcodeapp.base.BaseActivity;
import com.example.barcodeapp.interfaces.IBasePersenter;
import com.example.barcodeapp.interfaces.own.IOwn;
import com.example.barcodeapp.persenter.own.UpdateNamePresenter;
import com.example.barcodeapp.ui.wode.bean.JiFenListBean;
import com.example.barcodeapp.ui.wode.bean.UpDateNameBean;
import com.example.barcodeapp.utils.BirthdayToAgeUtil;
import com.example.barcodeapp.view.CustomDatePicker;
import com.example.barcodeapp.view.DateFormatUtils;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

public class PersonalActivity extends BaseActivity<IOwn.UpDateNamePresenter> implements View.OnClickListener, IOwn.UpDateNameView {
    private ImageView mImgHead;
    private PopupWindow pw;
    private boolean isCAMERA = false;//判断权限是否有
    private LinearLayout mllSex;
    private boolean isSex = true;//默认选中男  true ：男; false ：女;
    private TextView mTvNan;
    private TextView mtvSex1;
    private TextView mTvBaoCun;
    private TextView mTvAgeNum;
    private TextView mtvAge1Num;
    private Spinner mQieyeMingCheng;
    private TextView mTvSetPwd;
    private TextView mTvUpDateMusicLevel;
    private TextView mTvAge1;
    private TextView mTvUpdatePhoneNumber;
    private TextView mTvPhoneNumber;
    private TextView mTvWeiXinBind;
    private ImageView mIvNullNickName;
    private ImageView mIvAge;
    private ImageView mIvAge1;
    private LinearLayout mllAge;
    private LinearLayout mllName;
    private EditText mEtNickName;
    private TextView mTvUpdatePhoneUnmber;
    private TextView mTvCancel;
    private CustomDatePicker mDatePicker;
    private ArrayList<String> musicalLevelList;
    private Bitmap bm;

    @Override
    protected int getLayout() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initView() {
        setPermission();
        initCustomDatePicker();
        mImgHead = findViewById(R.id.img_head);
        mllSex = findViewById(R.id.ll_sex);
        mTvNan = findViewById(R.id.tv_nan);
        mtvSex1 = findViewById(R.id.tv_sex1);
        mTvBaoCun = findViewById(R.id.tv_baocun);
        mllAge = findViewById(R.id.ll_age);
        mTvCancel = findViewById(R.id.tv_cancel);
        mIvAge1 = findViewById(R.id.iv_age1);
        mllName = findViewById(R.id.ll_name);
        mTvWeiXinBind = findViewById(R.id.tv_weixinbind);
        mIvAge = findViewById(R.id.iv_age);
        mEtNickName = findViewById(R.id.et_nickname);
        mIvNullNickName = findViewById(R.id.iv_null_nickname);
        mTvAgeNum = findViewById(R.id.tv_age_num);
        mtvAge1Num = findViewById(R.id.tv_age1_num);
        mQieyeMingCheng = findViewById(R.id.qieye_mingcheng);
        mTvSetPwd = findViewById(R.id.tv_setpwd);
        mTvUpDateMusicLevel = findViewById(R.id.tv_update_music_level);
        mTvAge1 = findViewById(R.id.tv_age1);
        mTvUpdatePhoneNumber = findViewById(R.id.tv_update_phone_number);
        mTvPhoneNumber = findViewById(R.id.tv_phone_number);
        mTvUpdatePhoneUnmber = findViewById(R.id.tv_update_phone_unmber);
        if (mEtNickName.getText().toString().isEmpty()) {
            mIvNullNickName.setVisibility(View.VISIBLE);
            mEtNickName.setVisibility(View.GONE);
        } else {
            mIvNullNickName.setVisibility(View.GONE);
            mEtNickName.setVisibility(View.VISIBLE);
        }
        initListener();
        initList();
    }

    //初始化音乐水平弹窗
    private void initList() {
        musicalLevelList = new ArrayList<>();
        musicalLevelList.add("0基础");
        musicalLevelList.add("乐器/声乐 考级1级~3级");
        musicalLevelList.add("乐器/声乐 考级3级~6级");
        //第二步：为下拉列表定义一个适配器
        ArrayAdapter adapter = new ArrayAdapter(PersonalActivity.this, android.R.layout.simple_spinner_item, musicalLevelList);
        //第三步：设置下拉列表下拉时的菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        mQieyeMingCheng.setAdapter(adapter);
        //第五步：添加监听器，为下拉列表设置事件的响应
        mQieyeMingCheng.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //初始化生日选择器
    private void initCustomDatePicker() {
        long beginTimestamp = DateFormatUtils.str2Long("1990-01-01", false);
        long endTimestamp = System.currentTimeMillis();
        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                String age = new BirthdayToAgeUtil().BirthdayToAge(DateFormatUtils.long2Str(timestamp, false));
                mtvAge1Num.setText(age + "岁");
                mtvAge1Num.setVisibility(View.VISIBLE);
                mIvAge1.setVisibility(View.GONE);
                mTvAgeNum.setVisibility(View.GONE);
                mTvAge1.setText(DateFormatUtils.long2Str(timestamp, false));
            }
        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(false);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    //请求所需要的权限
    private void setPermission() {
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permission) {
                //请求权限成功
                isCAMERA = true;
            }

            @Override
            public void permissionDenied(@NonNull String[] permission) {
                //权限请求失败
                isCAMERA = false;
            }
        }, new String[]{Manifest.permission.CAMERA});
    }

    //所有监听
    private void initListener() {
        mImgHead.setOnClickListener(this);
        mllSex.setOnClickListener(this);
        mTvUpdatePhoneUnmber.setOnClickListener(this);
        mllAge.setOnClickListener(this);
        mTvUpdatePhoneNumber.setOnClickListener(this);
        mTvSetPwd.setOnClickListener(this);
        mTvUpDateMusicLevel.setOnClickListener(this);
        mllName.setOnClickListener(this);
        mTvCancel.setOnClickListener(this);
        mTvBaoCun.setOnClickListener(this);
        mTvWeiXinBind.setOnClickListener(this);
    }


    @Override
    protected UpdateNamePresenter initPersenter() {
        return new UpdateNamePresenter();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://相机图片
                if (resultCode == RESULT_OK) {
                    bm = (Bitmap) data.getExtras().get("data");
                    mImgHead.setImageBitmap(bm);
                }
                break;
            case 2://相册图片
                if (resultCode == RESULT_OK) {
                    //获取选中文件的定位符
                    Uri uri = data.getData();
                    Log.e("uri", uri.toString());
                    //使用content的接口
                    ContentResolver cr = this.getContentResolver();
                    try {
                        //获取图片
                        bm = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        mImgHead.setImageBitmap(bm);
                    } catch (Exception e) {
                        Log.e("Exception", e.getMessage(), e);
                    }
                } else {
                    //操作错误或没有选择图片
                    Log.i("MainActivtiy", "operation error");
                }
                break;
            case 3:
                if (data != null) {
                    String phoneNumber = data.getStringExtra("phoneNumber");
                    if (phoneNumber != null) {
                        String newPhoneNumber = setNewPhoneNumber(phoneNumber);
                        mTvPhoneNumber.setText(newPhoneNumber);
                    }
                }
                break;
        }
    }

    public String setNewPhoneNumber(String oldPhoneNumber) {
        String phoneNumber = oldPhoneNumber.substring(0, 3) + "****" + oldPhoneNumber.substring(7, oldPhoneNumber.length());
        return phoneNumber;
    }

    public void bgAlpha(float bgAlpha) {
        WindowManager.LayoutParams ab = getWindow().getAttributes();
        ab.alpha = bgAlpha;
        getWindow().setAttributes(ab);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_head://选择头像
                setHeadImgPopupWindow();
                break;
            case R.id.ll_sex://选择性别
                setSexSelectPopupWindow();
                break;
            case R.id.tv_update_phone_number://绑定手机
            case R.id.tv_update_phone_unmber://修改绑定手机
                Intent intent = new Intent(this, UpDatePhoneNamberActivity.class);
                startActivityForResult(intent, 3);
                break;
            case R.id.ll_age://选择年龄
                // 日期格式为yyyy-MM-dd
                mDatePicker.show(mTvAge1.getText().toString());
                break;
            case R.id.tv_setpwd://设置密码
                Intent intent1 = new Intent(PersonalActivity.this, SetLoginPasswordActivity.class);
                startActivity(intent1);
                break;
            case R.id.tv_update_music_level://选择音乐水平
                mQieyeMingCheng.performClick();
                break;
            case R.id.ll_name://输入昵称
                mIvNullNickName.setVisibility(View.GONE);
                mEtNickName.setVisibility(View.VISIBLE);
                mEtNickName.setFocusable(true);
                mEtNickName.setFocusableInTouchMode(true);
                mEtNickName.requestFocus();
                break;
            case R.id.tv_cancel://取消
                PersonalActivity.this.finish();
                break;
            case R.id.tv_baocun://保存
                String name = mEtNickName.getText().toString();
                if (!name.isEmpty()) {
                    persenter.getUpDateName("2", name);
                }
                break;
            case R.id.tv_weixinbind://绑定微信
                wxLogin();
                break;
        }
    }

    private static final String APP_ID = "wx98d1ea068e0d552b";
    private IWXAPI api;

    //微信登录页
    private void wxLogin() {
        //注册微信
        regToWx();
        //判断是否安装微信
        if (!api.isWXAppInstalled()) {
            Toast.makeText(mContext, "请安装微信", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(this, MyDialogActivity.class);
//            startActivity(intent);
        } else {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            api.sendReq(req);
        }
    }

    private void regToWx() {
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);
    }

    //选择头像弹窗
    private void setHeadImgPopupWindow() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.popupwindow_head_img_selected, null);
        LinearLayout mllPhotograph = inflate.findViewById(R.id.ll_photograph);
        LinearLayout mllPhotoAlbum = inflate.findViewById(R.id.ll_photo_album);
        ImageView mIvDismiss = inflate.findViewById(R.id.iv_dismiss);
        //选择相机中的图片
        mllPhotograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCAMERA) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量， 启动相机的关键
                    startActivityForResult(openCameraIntent, 1);
                    if (pw != null) {
                        pw.dismiss();
                    }
                } else {
                    setPermission();
                }
            }
        });
        //选择相册中的图片
        mllPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //intent可以应用于广播和发起意图，其中属性有：ComponentName,action,data等
                Intent intent = new Intent();
                intent.setType("image/*");
                //action表示intent的类型，可以是查看、删除、发布或其他情况；我们选择ACTION_GET_CONTENT，系统可以根据Type类型来调用系统程序选择Type
                //类型的内容给你选择
                intent.setAction(Intent.ACTION_GET_CONTENT);
                //如果第二个参数大于或等于0，那么当用户操作完成后会返回到本程序的onActivityResult方法
                startActivityForResult(intent, 2);
                if (pw != null) {
                    pw.dismiss();
                }
            }
        });
        //关闭弹窗
        mIvDismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pw != null) {
                    pw.dismiss();
                }
            }
        });
        int width = getPopupwindoWidth();
        pw = new PopupWindow(inflate, width - 100, WindowManager.LayoutParams.WRAP_CONTENT);
        bgAlpha(0.5f);
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bgAlpha(1f);
            }
        });
        pw.showAtLocation(mImgHead, Gravity.CENTER, 0, 0);
    }

    //选择性别弹窗
    private void setSexSelectPopupWindow() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.popupwindow_sex_selected, null);
        LinearLayout mllSexMan = inflate.findViewById(R.id.ll_sex_man);
        LinearLayout mllSexWoman = inflate.findViewById(R.id.ll_sex_woman);
        TextView mIvEnter = inflate.findViewById(R.id.tv_enter);
        ImageView mIvMan = inflate.findViewById(R.id.iv_man);
        ImageView mIvWoMan = inflate.findViewById(R.id.iv_woman);
        if (isSex) {
            mIvMan.setImageResource(R.mipmap.select_man);
            mIvWoMan.setImageResource(R.mipmap.notselect_woman);
        } else {
            mIvMan.setImageResource(R.mipmap.notselect_man);
            mIvWoMan.setImageResource(R.mipmap.select_woman);
        }
        //选择男
        mllSexMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSex = true;
                mIvMan.setImageResource(R.mipmap.select_man);
                mIvWoMan.setImageResource(R.mipmap.notselect_woman);
            }
        });
        //选择女
        mllSexWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSex = false;
                mIvMan.setImageResource(R.mipmap.notselect_man);
                mIvWoMan.setImageResource(R.mipmap.select_woman);
            }
        });
        //确定
        mIvEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIvAge.setVisibility(View.GONE);
                mTvNan.setVisibility(View.GONE);
                if (isSex) {
                    mtvSex1.setText("男");
                    mtvSex1.setVisibility(View.VISIBLE);
                } else {
                    mtvSex1.setText("女");
                    mtvSex1.setVisibility(View.VISIBLE);
                }
                pw.dismiss();
            }
        });
        int width = getPopupwindoWidth();
        pw = new PopupWindow(inflate, width - 100, WindowManager.LayoutParams.WRAP_CONTENT);
        bgAlpha(0.5f);
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bgAlpha(1f);
            }
        });
        pw.showAtLocation(mImgHead, Gravity.CENTER, 0, 0);
    }

    public int getPopupwindoWidth() {
        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        int width = defaultDisplay.getWidth();
        return width;
    }

    @Override
    public void getUpDateNameBean(UpDateNameBean upDateNameBean) {
        String status = upDateNameBean.getStatus();
        if (status.equals("1")) {
            Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
            PersonalActivity.this.finish();
        } else {
            Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
}
